//
//  mcrmSAASDataOperation.m
//  mcrmSAAS
//
//  Created by wjxfhxy on 14-6-3.
//  Copyright (c) 2014年 GuangZhouXuanWu. All rights reserved.
//

#import "RSWDataOperation.h"
#import "RSWDBOperation.h"
#import "PinyinSortProtocol.h" 

@implementation RSWDataOperation

-(void)modifyMyinfoByInfo:(MyInfo*)myInfo headFilePath:(NSString*)headFilePath completion:(void(^)(NSInteger nResult,BOOL bResult,NSError *error))completion
{
    EDOMRequestStateType stateType = [super requestAsyncBlock:^
    {
        [super progressViewBegin];
        
        __block NSInteger thisnResult = FALSE;
        __block BOOL thisbResult = FALSE;
        __block NSError *thisError = nil;
        
        RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
        
        NSString *token = [XLGContext context].m_token;
        [ser modifyMyinfoByInfo:myInfo token:token completion:^(NSInteger nResult, BOOL bResult, NSError *error)
         {
             thisnResult = nResult;
             thisbResult = bResult;
             thisError = error;
         }];
        
        if(thisnResult == YES)
        {
            RSWDataOperation *manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];

            NSInteger result = [manager refreshMyInfo];
            if(result == YES && ![headFilePath isEqualToString:@""])
            {
                [CCurrentUser copyAndCacheNewHeadImagePath:headFilePath withNewFileName:[myInfo.logoURL lastPathComponent]];
            }
        }
        
        [self requestResult:thisnResult output:nil error:thisError completion:^(NSInteger nResult, id output, NSError *error)
         {
             completion(thisnResult,thisbResult,thisError);
         }];
        
        [self detachDataOperationManager:@[ser]];
        
        [super progressViewEnd];
    }];
    if(stateType == EDOMRequestStateTypeCanNotRequest)
        completion(TERMINATEREADWRITE,NO,nil);
}


-(void)modifyUserHeadImage:(NSString*)filePath logoURL:(NSString*)logoURL completion:(void(^)(NSInteger nResult,BOOL bResult,NSError *error))completion
{
    [super requestThreadBlock:^
     {
         [super progressViewBegin:@"modifyUserHeadImage"];
         
         __block NSInteger thisnResult = FALSE;
         __block BOOL thisbResult = FALSE;
         __block NSError *thisError = nil;
         
         NSString *token = [XLGContext context].m_token;
         RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
         
         [ser modifyUserHeadImage:logoURL token:token completion:^(NSInteger nResult, BOOL bResult, NSError *error)
          {
              thisnResult = nResult;
              thisbResult = bResult;
              thisError = error;
          }];

        if(thisnResult == YES)
         {
             RSWDataOperation *manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];

             NSInteger result = [manager refreshMyInfo];
             if(result == YES && ![filePath isEqualToString:@""])
             {
                 [CCurrentUser copyAndCacheNewHeadImagePath:filePath withNewFileName:[logoURL lastPathComponent]];
             }
         }
         
         [self requestResult:thisnResult output:nil error:thisError completion:^(NSInteger nResult, id output, NSError *error)
          {
              completion(thisnResult,thisbResult,thisError);
          }];
         
         [self detachDataOperationManager:@[ser]];
         
         [super progressViewEnd];
     }];
}

-(void)modifyPasswordWithOldPassword:(NSString*)oldPassword newPassword:(NSString*)newPassword completion:(void(^)(NSInteger nResult,BOOL bResult,NSError *error))completion
{
    EDOMRequestStateType stateType = [super requestAsyncBlock:^
    {
        [super progressViewBegin];
        
        __block NSInteger thisnResult = FALSE;
        __block BOOL thisbResult = FALSE;
        __block NSError *thisError = nil;
        
        RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
        NSString *token = [XLGContext context].m_token;
        
        [ser modifyPasswordWithOldPassword:oldPassword newPassword:newPassword token:token completion:^(NSInteger nResult, BOOL bResult, NSError *error)
         {
             thisnResult = nResult;
             thisbResult = bResult;
             thisError = error;
         }];
        
        if(thisnResult == YES)
        {
            XLGLoginCommonProcess *um = [XLGLoginCommonProcess new];
            [um newlocalPassword:newPassword];
        }
        
        [self requestResult:thisnResult output:nil error:thisError completion:^(NSInteger nResult, id output, NSError *error)
         {
             completion(thisnResult,thisbResult,thisError);
         }];
        
        [self detachDataOperationManager:@[ser]];
        
        [super progressViewEnd];
    }];
    if(stateType == EDOMRequestStateTypeCanNotRequest)
        completion(TERMINATEREADWRITE,NO,nil);
}

- (NSArray*) uploadImage:(NSArray*)imgArray paras:(NSArray*)paras
{
    NSMutableArray *fileIdArray = [NSMutableArray new];
    if(imgArray.count > 0)
    {
        NSInteger thisResult = FALSE;
        
        for(NSString *imagePath in imgArray)
        {
            XLGPackFileUp *fileUp = [[XLGPackFileUp alloc] initWithDataOperationManagerDelegate:nil AttachDOM:self];
            if(fileUp != nil)
            {
                XLGResult * r = [fileUp uploadFileWithPath:imagePath paras:paras];
                [self detachDataOperationManager:@[fileUp]];
                
                thisResult = r.outResult;
                if(thisResult == YES && ((NSString*)r.outObj).length > 0)
                    [fileIdArray addObject:r.outObj];
                
                if(thisResult != YES)
                    break;
            }
        }
    }
    
    return fileIdArray;
}

-(void)userFeedBackWithFeedContent:(NSString*)content completion:(void(^)(NSInteger nResult,BOOL bResult,NSError *error))completion
{
    EDOMRequestStateType stateType = [super requestAsyncBlock:^
    {
        [super progressViewBegin];
        
        __block NSInteger thisnResult = FALSE;
        __block NSInteger thisbResult = FALSE;
        __block NSError * thisError = nil;
        
        RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
        NSString *token = [XLGContext context].m_token;
        
        [ser userFeedBackWithFeedContent:content token:token completion:^(NSInteger nResult, BOOL bResult, NSError *error)
             {
                 thisnResult = nResult;
                 thisbResult = bResult;
                 thisError = error;
             }];
        
        [self detachDataOperationManager:@[ser]];

        [self requestResult:thisnResult output:nil error:thisError completion:^(NSInteger nResult, id output, NSError *error)
         {
             completion(thisnResult,thisbResult,thisError);
         }];
        
        [super progressViewEnd];
    }];
    if(stateType == EDOMRequestStateTypeCanNotRequest)
        completion(TERMINATEREADWRITE,NO,nil);
}

-(void)getOnlineUserListCompletion:(void (^)(NSInteger, NSArray *,NSError *error))completion
{
    EDOMRequestStateType stateType =
    [super requestAsyncBlock:^
     {
         __block NSInteger thisnResult = FALSE;
         __block NSArray *thisList = nil;
         __block NSError *thisError = nil;
         
         RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
         NSString *token = [XLGContext context].m_token;

         XLGResult *r = [ser getOnlineUserList:token];
         thisnResult = r.outResult;
         thisList = r.outObj;
         thisError = r.outError;
         
         [super requestResult:thisnResult output:thisList error:nil completion:^(NSInteger nResult, id output, NSError *error)
          {
              completion(thisnResult,thisList,error);
          }];
     }];
    if(stateType == EDOMRequestStateTypeCanNotRequest)
        completion(TERMINATEREADWRITE,nil,nil);
}

- (XMSQueueDictionary *)groupBySortPinyinPorperty:(NSArray *)contacts
{
    XMSQueueDictionary *thisDic = nil;
    thisDic = [XMSQueueDictionary new];
    NSArray *ar = contacts;
    [ar enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         id<PinyinSortProtocol> p = obj;
         NSString *s = p.pinyinValue;
         if (s.length > 0)
         {
             s = [s substringToIndex:1];
             unichar szPy = [s characterAtIndex:0];
             
             if ((szPy < 'a' || szPy > 'z') && (szPy < 'A' || szPy > 'Z'))
                 s = @"#";
             else
                 s = [s uppercaseString];
         }
         else
             s = @"#";
         
         XMSKvPair *pair = [thisDic kvPairAtKey:s];
         if (pair == nil)
         {
             [thisDic addKey:s value:[[NSMutableArray alloc] initWithObjects:p, nil]];
         } else
         {
             BOOL f = NO;
             NSMutableArray *ar = pair.idValue;
             if(p.nameValue.length > 0)
             {
                 NSString *name = [p.nameValue substringWithRange:NSMakeRange(0, 1)];
                 for(NSInteger i = ar.count - 1;i >= 0;i--)
                 {
                     NSString * n = ((id<PinyinSortProtocol>)ar[i]).nameValue;
                     if(n.length > 0)
                     {
                         n = [n substringWithRange:NSMakeRange(0, 1)];
                         if([name isEqualToString:n])
                         {
                             [ar insertObject:p atIndex:i+1];
                             f = YES;
                             break;
                         }
                     }
                     else
                     {
                         [ar addObject:p];
                     }
                 }
             }
             if(f == NO)
             {
                 [ar addObject:p];
             }
         }
     }];
    
    [thisDic.arQueue sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"idKey" ascending:YES]]];
    
    id i = [thisDic getValueForKey:@"#"];
    if (i != nil)
    {
        [thisDic removeObjectForKey:@"#"];
        [thisDic addKey:@"#" value:i];
    }
    return thisDic;
}

-(void)getEntAddressBookContactDetialWithContactNumber:(NSArray*)contactNumbers sort:(BOOL)sort completion:(void (^)(NSInteger nResult, NSArray *arList))completion
{
    EDOMRequestStateType stateType = [super requestAsyncBlock:^
    {
        RSWDBOperation *db = [RSWDBOperation new];
        XLGResult *r = [db getEntAddressBookContactDetialWithContactNumber:contactNumbers];
        id output = r.outObj;
        if(sort == YES)
        {
            output = [self groupBySortPinyinPorperty:output];
        }
        [super requestResult:r.outResult output:output error:nil completion:^(NSInteger nResult, id output, NSError *error)
         {
             completion(nResult,output);
         }];
    }];
    if(stateType == EDOMRequestStateTypeCanNotRequest)
        completion(TERMINATEREADWRITE,nil);
}

-(void)getEntAddressBookWithRefresh:(BOOL)bRefresh completion:(void(^)(NSInteger nResult,XMSQueueDictionary *list,NSError *error))completion
{
    EDOMRequestStateType stateType = [super requestAsyncBlock:^
      {
          __block NSInteger thisResult =FALSE;
          __block NSArray *thisList = nil;
          __block NSError *thisError = nil;
          
          if(bRefresh == YES)
          {
              [super pullRefreshViewBegin];
              
              NSString *token = [XLGContext context].m_token;
              NSString *deptId = [[MyInfo myInfo].departmentId toNSString];
              if(deptId == nil)
                  deptId = @"";
              
              XLGResult *r = [self refreshEntAddressBookWithToken:token deptId:deptId];
              
              thisResult = r.outResult;
              thisError = r.outError;
              
              if(thisResult == YES &&self.isCanRequest != YES)
                  thisResult =TERMINATEREADWRITE;
              
              [super pullRefreshViewEnd];
          }
          else
              thisResult = YES;
          
          XMSQueueDictionary *thisDic = nil;
          if(thisResult == YES)
          {
              RSWDBOperation *db = [RSWDBOperation new];
              XLGResult *r = [db getEntAddressBookContact];
              thisResult = r.outResult;
              thisList = r.outObjArray;
              
              if(thisResult == YES)
              {
                  thisDic = [self groupBySortPinyinPorperty:thisList];
              }
          }
          
          [super requestResult:thisResult output:thisDic error:thisError completion:completion];
      }];
    if(stateType == EDOMRequestStateTypeCanNotRequest)
        completion(TERMINATEREADWRITE,nil,nil);
}

- (NSString *)localPassword:(NSString *)szPath
{
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:szPath];
    int n = sizeof(char) * (int)data.length;
    char *buf = malloc(n);
    char *buffer = malloc(n / sizeof(int) + 1);
    [data getBytes:buf length:n];
    for (int i = 0; i < n; i += 4)
    {
        char f[4];
        memcpy(f, buf + i, 4);
        int ch = *(int *) f;
        ch /= 2;
        buffer[i / 4] = ch;
    }
    buffer[n / sizeof(int)] = '\0';
    NSString *psw = [NSString stringWithUTF8String:buffer];
    free(buf);
    free(buffer);
    return psw;
}

- (NSInteger)newlocalPassword:(NSString*)password
{
    [self savePasword:password];
    return YES;
}

- (void)savePasword:(NSString *)password
{
    NSString *path = [[XLGContext context].m_szUserpath stringByAppendingPathComponent:PSWF];
    const char *chPsw = [password UTF8String];
    size_t nLen = strlen(chPsw);
    NSMutableData *data = [[NSMutableData new] autorelease_mm];
    for (int i = 0; i < nLen; i++)
    {
        int ch = chPsw[i];
        ch *= 2;
        [data appendBytes:&ch length:sizeof(int)];
    }
    [[NSFileManager defaultManager] createFileAtPath:path contents:data attributes:nil];
}
@end
